import random
import numpy as np
import torch
import torch.nn.functional as F

from algo import rl_utils
from env1 import  MECEnv

def norm_state(state):
     return  state / torch.tensor([[[3000, 4, 1, 5, 1, 20e5, 2]]])


class PolicyNet(torch.nn.Module):
    def __init__(self, state_dim, hidden_dim, action_dim):
        super(PolicyNet, self).__init__()
        self.fc1 = torch.nn.Linear(state_dim, hidden_dim)
        self.fc2 = torch.nn.Linear(hidden_dim, hidden_dim)
        self.fc3 = torch.nn.Linear(hidden_dim, action_dim)

        self.apply(self._init_weights)

    def _init_weights(self, module):
        if isinstance(module, torch.nn.Linear):
            # module.weight.data.normal_(mean=0.0, std=1.0)
            torch.nn.init.xavier_uniform_(module.weight)

    def forward(self, x):
        x = norm_state(x)
        x = F.relu(self.fc1(x))
        x = F.tanh(self.fc2(x))
        out = self.fc3(x)
        res = F.softmax(out, dim=2)
        return res


class QValueNet(torch.nn.Module):
    ''' 只有一层隐藏层的Q网络 '''

    def __init__(self, state_dim, hidden_dim, action_dim):
        super(QValueNet, self).__init__()
        self.fc1 = torch.nn.Linear(state_dim, hidden_dim)
        self.fc2 = torch.nn.Linear(hidden_dim, hidden_dim)
        self.fc3 = torch.nn.Linear(hidden_dim, action_dim)

    def forward(self, x):
        x = norm_state(x)
        x = F.relu(self.fc1(x))
        x = F.tanh(self.fc2(x))
        return self.fc3(x)


class SAC:
    ''' 处理离散动作的SAC算法 '''

    def __init__(self, state_dim, hidden_dim, action_dim, actor_lr, critic_lr,
                 alpha_lr, target_entropy, tau, gamma, device):
        # 策略网络
        self.actor = PolicyNet(state_dim, hidden_dim, action_dim).to(device)
        # 第一个Q网络
        self.critic_1 = QValueNet(state_dim, hidden_dim, action_dim).to(device)
        # 第二个Q网络
        self.critic_2 = QValueNet(state_dim, hidden_dim, action_dim).to(device)
        self.target_critic_1 = QValueNet(state_dim, hidden_dim,
                                         action_dim).to(device)  # 第一个目标Q网络
        self.target_critic_2 = QValueNet(state_dim, hidden_dim,
                                         action_dim).to(device)  # 第二个目标Q网络
        # 令目标Q网络的初始参数和Q网络一样
        self.target_critic_1.load_state_dict(self.critic_1.state_dict())
        self.target_critic_2.load_state_dict(self.critic_2.state_dict())
        self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),
                                                lr=actor_lr)
        self.critic_1_optimizer = torch.optim.Adam(self.critic_1.parameters(),
                                                   lr=critic_lr)
        self.critic_2_optimizer = torch.optim.Adam(self.critic_2.parameters(),
                                                   lr=critic_lr)
        # 使用alpha的log值,可以使训练结果比较稳定
        self.log_alpha = torch.tensor(np.log(0.01), dtype=torch.float)
        self.log_alpha.requires_grad = True  # 可以对alpha求梯度
        self.log_alpha_optimizer = torch.optim.Adam([self.log_alpha],
                                                    lr=alpha_lr)
        self.target_entropy = target_entropy  # 目标熵的大小
        self.gamma = gamma
        self.tau = tau
        self.device = device

    def take_action(self, state):
        state = torch.tensor([state], dtype=torch.float).to(self.device)
        probs = self.actor(state)
        # print(probs)
        action_dist = torch.distributions.Categorical(probs)
        action = action_dist.sample()
        return [action.item()]

    # 计算目标Q值,直接用策略网络的输出概率进行期望计算
    def calc_target(self, rewards, next_states, dones):
        next_probs = self.actor(next_states)
        next_log_probs = torch.log(next_probs + 1e-8)
        _ = next_probs * next_log_probs
        entropy = -torch.sum(_, dim=2, keepdim=True)
        q1_value = self.target_critic_1(next_states)
        q2_value = self.target_critic_2(next_states)
        min_value = torch.min(q1_value, q2_value)
        min_qvalue = torch.sum(next_probs * min_value,
                               dim=2,
                               keepdim=True)
        next_value = min_qvalue + self.log_alpha.exp() * entropy
        td_target = rewards.view(-1,1,1) + self.gamma * next_value * (1 - dones.view(-1,1,1))
        return td_target

    def soft_update(self, net, target_net):
        for param_target, param in zip(target_net.parameters(),
                                       net.parameters()):
            param_target.data.copy_(param_target.data * (1.0 - self.tau) +
                                    param.data * self.tau)

# todo 验证其他地方 state
    def update(self, transition_dict):
        states = torch.tensor(transition_dict['states'],
                              dtype=torch.float).to(self.device)
        actions = torch.tensor(transition_dict['actions']).view(-1,1, 1).to(
            self.device)  # 动作不再是float类型
        rewards = torch.tensor(transition_dict['rewards'],
                               dtype=torch.float).view(-1, 1).to(self.device)
        next_states = torch.tensor(transition_dict['next_states'],
                                   dtype=torch.float).to(self.device)
        dones = torch.tensor(transition_dict['dones'],
                             dtype=torch.float).view(-1, 1).to(self.device)

        # 更新两个Q网络
        td_target = self.calc_target(rewards, next_states, dones)
        _ = self.critic_1(states)
        critic_1_q_values = _.gather(2, actions)
        f_l = F.mse_loss(critic_1_q_values, td_target.detach())
        critic_1_loss = torch.mean(f_l)
        critic_2_q_values = self.critic_2(states).gather(2, actions)
        critic_2_loss = torch.mean(
            F.mse_loss(critic_2_q_values, td_target.detach()))
        self.critic_1_optimizer.zero_grad()
        critic_1_loss.backward()
        self.critic_1_optimizer.step()
        self.critic_2_optimizer.zero_grad()
        critic_2_loss.backward()
        self.critic_2_optimizer.step()

        # 更新策略网络
        # todo 解决不同的 state 输出的 probs 相同的问题
        probs = self.actor(states)
        print(probs)
        log_probs = torch.log(probs + 1e-8)
        # 直接根据概率计算熵
        _ = probs * log_probs
        entropy = -torch.sum(_, dim=2, keepdim=True)  #
        q1_value = self.critic_1(states)
        q2_value = self.critic_2(states)
        min = torch.min(q1_value, q2_value)
        min_qvalue = torch.sum(probs * min,
                               dim=2,
                               keepdim=True)  # 直接根据概率计算期望
        # actor_loss = torch.mean(-self.log_alpha.exp() * entropy - min_qvalue)
        loss_before = -self.log_alpha.exp() * entropy - min_qvalue
        # actor_loss = torch.mean(loss_before)
        actor_loss = loss_before.sum(dim=-1)
        actor_loss = actor_loss.mean()
        self.actor_optimizer.zero_grad()
        actor_loss.backward()
        self.actor_optimizer.step()

        # 更新alpha值
        alpha_loss = torch.mean(
            (entropy - target_entropy).detach() * self.log_alpha.exp())
        self.log_alpha_optimizer.zero_grad()
        alpha_loss.backward()
        self.log_alpha_optimizer.step()

        self.soft_update(self.critic_1, self.target_critic_1)
        self.soft_update(self.critic_2, self.target_critic_2)
        return actor_loss.item() ,critic_1_loss.item(), critic_2_loss.item(), min.mean().item()




if __name__ == "__main__":

    # actor_lr = 1e-2
    # critic_lr = 1e-4
    # alpha_lr = 1e-4
    actor_lr  = 8e-6
    critic_lr = 5e-4
    alpha_lr = 8e-4
    num_episodes = 200
    hidden_dim = 128
    gamma = 0.98
    tau = 0.005  # 软更新参数
    buffer_size = 10000
    minimal_size = 500
    batch_size = 64
    target_entropy = -1
    device = torch.device("cuda") if torch.cuda.is_available() else torch.device(
        "cpu")

    env = MECEnv.env(1,3)
    random.seed(0)
    np.random.seed(0)
    torch.manual_seed(0)
    replay_buffer = rl_utils.ReplayBuffer(buffer_size)
    state_dim = env.state_dim
    action_dim = env.action_dim
    agent = SAC(state_dim, hidden_dim, action_dim, actor_lr, critic_lr, alpha_lr,
                target_entropy, tau, gamma, device)

    return_list = rl_utils.train_off_policy_agent(env, agent, num_episodes,
                                                  replay_buffer, minimal_size,
                                                  batch_size)